package com.prb.consumer.register;

import com.prb.consumer.config.ClientContext;
import com.prb.consumer.config.ServerScanLoader;
import com.prb.register.factory.RpcRegistryFactory;
import com.prb.register.register.RpcRegistryHandler;
import com.prb.register.register.impl.ZookeeperRegistryHandler;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class RegisterContext implements InitializingBean {

    @Autowired
    private RpcRegistryFactory rpcRegistryFactory;

    private RpcRegistryHandler registryHandler;


    @Override
    public void afterPropertiesSet() throws Exception {
        registryHandler = rpcRegistryFactory.getObject();
    }


    public void registry(String service, String ip, int port) {

        registryHandler.registry(service , ip , port);

    }

    public List<String> discovery(String service) {

        return registryHandler.discovery(service);
    }


    public void addNodeChangeListener(String serverName){


        ZookeeperRegistryHandler zkHandler = (ZookeeperRegistryHandler) registryHandler;
        ZkClient client = zkHandler.getClient();

        //添加 节点监听
        client.subscribeChildChanges("/" + serverName , (nodeName , hostList) -> {

            //判断是否有新的 服务端 上线， 如果有则创建netty客户端
            for (String host : hostList) {
                //注册客户端
                if(ClientContext.clientMap.get(host) == null){
                    ClientContext.registerRpcClient(host);

                }
                //调用客户端不存在，进行创建，注册
                if(!ServerScanLoader.serverHostList.contains(host)){
                    ServerScanLoader.serverHostList.add(host);

                }

            }
            System.out.println("服务对应的主机列表 发生变更" + hostList);
            ServerScanLoader.serverHostMap.put(serverName , hostList);
        });

    }

}
